package cn.edu.scnu.semart.goods.service.Impl;

import cn.edu.scnu.semart.goods.service.GoodsService;
import cn.edu.scnu.semart.model.goods.Favorite;
import cn.edu.scnu.semart.goods.mapper.FavoriteMapper;
import cn.edu.scnu.semart.goods.service.FavoriteService;
import cn.edu.scnu.semart.model.goods.Goods;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户收藏Service实现类
 */
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {

    @Autowired
    private GoodsService goodsService;

    @Transactional
    @Override
    public boolean addFavorite(Integer userId, Integer goodsId) {
        Favorite existingFavorite = baseMapper.selectAnyFavorite(userId, goodsId);

        if (existingFavorite != null) {
            if (existingFavorite.getDeleted() == null || existingFavorite.getDeleted() == 0) {
                return false; // 已收藏
            }
            boolean restored = baseMapper.restoreFavorite(existingFavorite.getId()) > 0;
            if (restored) {
                goodsService.incrementFavoriteCount(goodsId); // 更新收藏数
            }
            return restored;
        }

        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setGoodsId(goodsId);

        boolean saved = save(favorite);
        if (saved) {
            goodsService.incrementFavoriteCount(goodsId); // 更新收藏数
        }
        return saved;
    }

    @Transactional
    @Override
    public boolean removeFavorite(Integer userId, Integer goodsId) {
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("goods_id", goodsId);
        boolean removed = remove(queryWrapper);
        if (removed) {
            goodsService.decrementFavoriteCount(goodsId); // 更新收藏数
        }
        return removed;
    }

    @Override
    public boolean isFavorite(Integer userId, Integer goodsId) {
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("goods_id", goodsId);
        return count(queryWrapper) > 0;
    }
    @Override
    public IPage<Goods> getUserFavorites(Integer userId, Page<Goods> page) {
        //查询收藏记录分页
        Page<Favorite> favoritePage = new Page<>(page.getCurrent(), page.getSize());
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .select("goods_id")
                .orderByDesc("create_time");

        IPage<Favorite> favorites = page(favoritePage, queryWrapper);

        //如果没有收藏记录，返回空分页
        if (favorites.getRecords().isEmpty()) {
            return new Page<>(page.getCurrent(), page.getSize(), 0);
        }

        //提取商品ID列表
        List<Integer> goodsIds = favorites.getRecords().stream()
                .map(Favorite::getGoodsId)
                .collect(Collectors.toList());

        //批量查询商品详情
        List<Goods> goodsList = goodsService.getBatchByIds(goodsIds);

        //构建返回的分页结果
        Page<Goods> resultPage = new Page<>(page.getCurrent(), page.getSize(), favorites.getTotal());
        resultPage.setRecords(goodsList);

        return resultPage;
    }

    @Override
    public Integer getUserFavoriteCount(Integer userId) {
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return (int) count(queryWrapper);
    }
} 